<template>
  <div class="notice-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>公告管理</span>
          <el-button type="primary" @click="showAddDialog">发布公告</el-button>
        </div>
      </template>
      
      <!-- 公告列表 -->
      <el-table :data="notices" style="width: 100%" v-loading="loading">
        <el-table-column prop="content" label="内容" show-overflow-tooltip />
        <el-table-column prop="publishdate" label="发布时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.publishdate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑公告对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="noticeForm" :rules="rules" ref="noticeFormRef" label-width="80px">
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="noticeForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入公告内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllNotices, addNotice, updateNotice, deleteNotice } from '../../api/notice'

const notices = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('发布公告')
const noticeFormRef = ref(null)

const noticeForm = ref({
  noticeid: null,
  content: ''
})

const rules = {
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { min: 5, max: 500, message: '内容长度在 5 到 500 个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取所有公告
const fetchNotices = async () => {
  loading.value = true
  try {
    const res = await getAllNotices()
    if (res.code === 200) {
      notices.value = res.data.sort((a, b) => 
        new Date(b.publishdate) - new Date(a.publishdate)
      )
    }
  } catch (error) {
    ElMessage.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '发布公告'
  noticeForm.value = {
    noticeid: null,
    content: ''
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑公告'
  noticeForm.value = { ...row }
  dialogVisible.value = true
}

// 提交表单（添加/编辑）
const handleSubmit = async () => {
  if (!noticeFormRef.value) return
  
  await noticeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (noticeForm.value.noticeid) {
          // 编辑
          const res = await updateNotice(noticeForm.value.noticeid, noticeForm.value)
          if (res.code === 200) {
            ElMessage.success('更新成功')
          }
        } else {
          // 添加
          const res = await addNotice(noticeForm.value)
          if (res.code === 201) {
            ElMessage.success('发布成功')
          }
        }
        dialogVisible.value = false
        fetchNotices()
      } catch (error) {
        ElMessage.error(noticeForm.value.noticeid ? '更新失败' : '发布失败')
      }
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这条公告吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteNotice(row.noticeid)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchNotices()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchNotices()
})
</script>

<style scoped>
.notice-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 